package com.cjst.controller.sys;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.sys.SysDict;
import com.cjst.sdp.util.MapUtils;
import com.cjst.service.sys.SysDictService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.code.PageUtil;
import com.cjst.util.common.Common;
import com.cjst.util.json.ResultObj;

/**
 * 字典管理
 *
 * @author szbj001
 */
@Controller
@RequestMapping("/sys/sysDict")
public class SysDictController extends BaseController {

    private static final String SESSION_DICT = "dict";

    @Autowired
    private SysDictService sysDictService;

    /**
     * 字典详情
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @RequiresPermissions("dict")
    public String toDict() {
        return "system/dict/dict";
    }

    /**
     * 列表数据
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object list(SysDict sysDict) {
        WherePrams wherePrams = Method.where("pid", C.EQ, "0");
        wherePrams.and("delFlag", C.EQ, "0");
        if (sysDict != null) {
            if (StringUtils.isNotEmpty(sysDict.getName())) {
                wherePrams.and("name", C.LIKE, sysDict.getName());
            }
        }
        PageUtil<SysDict> pageUtil = sysDictService.listPageCount(wherePrams);
        return super.packForBT(pageUtil);
    }


    /**
     * 新增页面
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @RequiresPermissions("dict_add")
    public String addDict() {
        return "system/dict/dict_add";
    }

    /**
     * 保存新增数据
     * @param dict
     * @param dictValues
     * @param req
     * @return
     */
    @RequestMapping(value = "/save/add", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("dict_add")
    public ResultObj addDict(SysDict dict, String dictValues, HttpServletRequest req) {
        if (dict == null || StringUtils.isEmpty(dict.getType())) {
            //throw new Exception("字典类型为空，添加字典失败");
            return new ResultObj(1, "字典类型为空，添加字典失败", null);
        }
        WherePrams where = Method.where("type", C.EQ, dict.getType());
        where.and("delFlag", C.EQ, "0");
        where.and("pid", C.EQ, "0");
        SysDict dict2 = sysDictService.get(where);
        if (dict2 != null) {
            return new ResultObj(1, "该字典已存在，添加字典失败", null);
        }
        ResultObj checkResult = dictKeyCheck(dictValues, dict);
        if (checkResult.getResultCode() == 1) {
            return checkResult;
        } else {
            String tips = (String) checkResult.getData();
            if (StringUtils.isNotEmpty(tips)) {
                dict.setTips(tips);
            }
        }
        boolean flag = sysDictService.addDict(dict, dictValues);
        log.info("============新增字典成功===============");
        return new ResultObj(0, "新增字典成功", flag);
    }

    /**
     * 修改字典页面
     * @param dictId
     * @param model
     * @return
     */
    @RequestMapping(value = "/update/{dictId}", method = RequestMethod.GET)
    @RequiresPermissions("dict_update")
    public String updateDict(@PathVariable String dictId, Model model) {
        WherePrams where = Method.where("id", C.EQ, dictId);
        SysDict dict = sysDictService.get(where);
        if (dict != null) {
            model.addAttribute("dict", dict);
            WherePrams wherePrams = Method.where("pid", C.EQ, dictId);
            wherePrams.orderBy("num");
            List<SysDict> dicts = sysDictService.list(wherePrams);
            if (dicts != null && dicts.size() > 0) {
                model.addAttribute("subDicts", dicts);
            } else {
                model.addAttribute("subDicts", null);
            }
        }
        return "system/dict/dict_edit";
    }

    /**
     * 查看字典详情
     * @param dictId
     * @param model
     * @return
     */
    @RequestMapping(value = "/view/{dictId}", method = RequestMethod.GET)
    @RequiresPermissions("dict_view")
    public String viewDict(@PathVariable String dictId, Model model) {
        WherePrams where = Method.where("id", C.EQ, dictId);
        SysDict dict = sysDictService.get(where);
        if (dict != null) {
            model.addAttribute("dict", dict);
            WherePrams wherePrams = Method.where("pid", C.EQ, dictId);
            wherePrams.orderBy("num");
            List<SysDict> dicts = sysDictService.list(wherePrams);
            if (dicts != null && dicts.size() > 0) {
                model.addAttribute("subDicts", dicts);
            } else {
                model.addAttribute("subDicts", null);
            }
        }
        return "system/dict/dict_view";
    }

    /**
     * 保存修改字典数据
     * @param dict
     * @param dictValues
     * @param req
     * @return
     */
    @RequestMapping(value = "/save/update", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("dict_update")
    public ResultObj editDict(@Valid SysDict dict, String dictValues, HttpServletRequest req) {
        if (dict == null || StringUtils.isEmpty(dict.getType())) {
            return new ResultObj(1, "参数传递错误", null);
        }
        WherePrams where = Method.where("type", C.EQ, dict.getType());
        where.and("id", C.EQ, dict.getId());
        SysDict dict2 = sysDictService.get(where);
        if (dict2 == null) {
            return new ResultObj(1, "该字典不存在，修改字典失败", null);
        }
        ResultObj checkResult = dictKeyCheck(dictValues, dict);
        if (checkResult.getResultCode() == 1) {
            return checkResult;
        } else {
            String tips = (String) checkResult.getData();
            if (StringUtils.isNotEmpty(tips)) {
                dict2.setTips(tips);
            }
        }

        dict2.setName(dict.getName());
        dict2.setType(dict.getType());
        boolean flag = sysDictService.updateDict(dict2, dictValues);
        log.info("============新增字典成功===============");
        return new ResultObj(0, "新增字典成功", flag);
    }

    /**
     * 删除字典及其值
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("dict_delete")
    @Transactional
    public ResultObj saveDelete(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ResultObj(1, "参数传递为空,删除字典失败", null);
        }
        String[] list = ids.split(",");
        for (String dictId : list) {
            WherePrams wherePrams = Method.where("id", C.EQ, dictId);
            wherePrams.or("pid", C.EQ, dictId);
            SysDict dict = new SysDict();
            dict.setDelFlag("1");
            sysDictService.updateLocal(dict, wherePrams);
        }

        return new ResultObj(0, "删除成功", true);

    }

    /**
     * 数据字典值检查，并返回拼接后的tips，排序的tips
     */
    public ResultObj dictKeyCheck(String dictValues, SysDict dict) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotEmpty(dictValues)) {
            String[] dicts = dictValues.split(";");
            for (String str : dicts) {
                String[] ss = str.split(":");
                if (map.containsKey(ss[0])) {
                    if (StringUtils.isNotEmpty(dict.getId())) {
                        //throw new Exception("值["+ss[0]+"]重复，修改字典失败");
                        return new ResultObj(1, "值[" + ss[0] + "]重复，修改字典失败", null);
                    } else {
                        return new ResultObj(1, "值[" + ss[0] + "]重复，添加字典失败", null);
                    }
                }
                map.put(ss[0], ss[1]);
            }
        }
        Map<String, String> resultMap = MapUtils.sortMapByKey(map);
        String tips = "";
        if (resultMap != null) {
            for (String key : resultMap.keySet()) {
                tips = tips + key + ":" + resultMap.get(key) + ";";
            }
        }
        return new ResultObj(0, "", tips);
    }

    /**
     * 全部字典数据
     * @param type
     * @param req
     * @return
     */
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    @ResponseBody
    public Object all(@RequestParam String type, HttpServletRequest req) {
        WherePrams wherePrams = Method.where("pid", C.NE, "0");
        wherePrams.and("delFlag", C.EQ, "0");
        if (Common.isNotEmpty(type)) {
            wherePrams.and("type", C.EQ, type);
        }
        wherePrams.orderBy("num asc");
        List<SysDict> list = sysDictService.list(wherePrams);
        return list;
    }

}
